package com.example.gomi.intelligentcitypipe.serial;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.example.gomi.intelligentcitypipe.DAO.PipeInfo;
import com.example.gomi.intelligentcitypipe.bean.Response;
import com.example.gomi.intelligentcitypipe.handler.MessageReceiveHandler;
import com.example.gomi.intelligentcitypipe.handler.PushThraad;
import com.example.gomi.intelligentcitypipe.utils.ResponseMessageUtils;

import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by gomi on 16-7-1.
 */
public class SerialController {
    private static SerialController ourInstance = null;

    private OddSetInterface uartInterface;

    private PipeInfo pipeInfo = new PipeInfo();

    private String version = UUID.randomUUID().toString();

    private PipeProtocol pipeProtocol = null;

    public static final List<Runnable> threadBox = new LinkedList<>();

    /**
     * 获取数据的操作是否在进行
     */
    private boolean mRunFlag = false;


    /**
     * 收到消息时的handler，从activity传入主要用于处理界面的效果等
     */
    private MessageReceiveHandler messageReceiveHandler;


    public static SerialController getInstance() {

        if (ourInstance == null) {
            ourInstance = new SerialController();
        }

        return ourInstance;
    }


    private SerialController() {
        uartInterface = new BluetoothInterface(this.version);
        pipeProtocol = new PipeProtocol(this.version);
    }

    public void DestroyAccessory() {
        uartInterface.stop();
        this.mRunFlag = false;
        pipeProtocol = null;
    }

    public void sendData(byte[] buffer) {

        if(uartInterface != null){
            uartInterface.SendData(buffer);
        }else{
            Log.e("SerialController","---线程已停止读取了.....");
        }
    }

    public void handleResponse(Response response) {
        Log.e("SerialController", "------head[" +ResponseMessageUtils.bytesToHex(response.getHead())+"],body["+ ResponseMessageUtils.bytesToHex(response.getBody())+"]   command:"+pipeProtocol.getCurrentCommand());
        response.setType(pipeProtocol.getCurrentCommand());
        ResponseMessageUtils.analyze(response, pipeInfo);
        Message message = messageReceiveHandler.obtainMessage();
        message.what = pipeProtocol.getCurrentCommand();
        message.obj = pipeInfo;
        message.sendToTarget();
        pipeProtocol.increaseReceivePackage();
        if (pipeInfo.checkPipeID()) {
            Log.e("SerialController", "------pipeInfo.checkPipeID() error..RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR.");
            //this.pause = true;
            //如果threadBox 为空了,当有一个的时候我就开始不再放了，因为没有意义。
            synchronized (threadBox) {
                if (threadBox.size() == 0) {
                    this.pause = true;
                    Runnable runnable = new PushThraad(pipeProtocol.getCurrentCommand());
                    threadBox.add(runnable);
                    new Thread(runnable).start();
                }
            }
        }else{
            Log.e("SerialController", "------pipeInfo.checkPipeID() error...");
        }
    }

    /**
     * 开始读取数据的操作
     *
     * @return
     */
    public boolean start() {
        Log.e("SerialController","開始讀取數據。。");
        setmRunFlag(true);
        if (pipeProtocol == null) {
            pipeProtocol = new PipeProtocol(this.version);
        }
        pipeProtocol.startGetPipeInfo();
        if (uartInterface == null) {
            uartInterface = new BluetoothInterface(this.version);
        }
        uartInterface.start();
        return true;
    }

    public void push() {
        this.pause = false;
        if(pipeProtocol != null){
            pipeProtocol.toNext();
        }
    }

    public boolean getmRunFlag() {
        return mRunFlag;
    }

    public void setmRunFlag(boolean flag) {
        this.mRunFlag = flag;
    }

    /**
     * 停止读取
     */
    public void stop() {
        this.setmRunFlag(false);
        uartInterface.stop();
        pipeProtocol = null;
        uartInterface = null;
        version = UUID.randomUUID().toString();
    }


    public MessageReceiveHandler getMessageReceiveHandler() {
        return messageReceiveHandler;
    }

    public void setMessageReceiveHandler(MessageReceiveHandler messageReceiveHandler) {
        this.messageReceiveHandler = messageReceiveHandler;
    }

    private boolean pause;

    public boolean getPause() {
        return pause;
    }

    public String getVersion() {
        return version;
    }
}
